package com.quanxiaoha.weblog.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.quanxiaoha.weblog.common.domain.entity.Article;
import com.quanxiaoha.weblog.common.domain.query.MemoryDataQuery;
import com.quanxiaoha.weblog.common.domain.query.SegmentQuery;
import com.quanxiaoha.weblog.common.domain.vo.MemoryDataVo;
import com.quanxiaoha.weblog.common.domain.vo.MergeQuery;
import com.quanxiaoha.weblog.common.domain.vo.ReadNumVo;
import com.quanxiaoha.weblog.common.domain.vo.SegmentVo;
import com.quanxiaoha.weblog.common.entity.ScheduleMemory;
import com.quanxiaoha.weblog.common.domain.mapper.ScheduleMemoryMapper;
import com.quanxiaoha.weblog.common.service.IScheduleMemoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quanxiaoha.weblog.common.service.IScheduleRewardService;
import com.quanxiaoha.weblog.common.utils.TextSplitterUtil;
import kotlin.jvm.internal.Lambda;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-06-24
 */
@Service
public class ScheduleMemoryServiceImpl extends ServiceImpl<ScheduleMemoryMapper, ScheduleMemory> implements IScheduleMemoryService {


    @Autowired
    private IScheduleRewardService scheduleRewardService;
//
//    @Override
//    public List<MemoryDataVo> getMemoryData() {
//
//        List<ScheduleMemory> list = this.list();
//        Map<String, List<ScheduleMemory>> memoryMap = list.stream().collect(Collectors.groupingBy(x -> x.getCategoryName()));
//        List<MemoryDataVo> segmentVoList = new ArrayList<>();
//        memoryMap.forEach((key, value) -> {
//            MemoryDataVo memoryDataVo = new MemoryDataVo();
//            memoryDataVo.setTitle(key);
//            memoryDataVo.setSegments(value.size()>0
//                    ?value.stream().map(x->{
//                SegmentVo segmentVo = new SegmentVo();
//                segmentVo.setId(x.getId());
//                segmentVo.setOrder(Objects.isNull(x.getContent())?0:x.getContent().length());
//                segmentVo.setTitle(x.getTitle());
//                segmentVo.setContent(x.getContent());
//                segmentVo.setReadNum(x.getReadNum());
//                if(x.getReadNum()>10){
//                    segmentVo.setIsShow(false);
//                }
//                return segmentVo;
//            }).filter(x->x.getIsShow()).collect(Collectors.toList())
//                    :new ArrayList<>());
//            memoryDataVo.setSegmentCount(memoryDataVo.getSegments().size());
//            if(memoryDataVo.getSegmentCount()==0){
//                memoryDataVo.setType(2);
//            }
//            segmentVoList.add(memoryDataVo);
//        });
//        return segmentVoList;
//    }

    @Override
    public List<MemoryDataVo> getMemoryData() {

        //查询数据
        QueryWrapper<ScheduleMemory> qw = new QueryWrapper<>();
        qw.select("id", "title", "category_name", "read_num");
        List<ScheduleMemory> list = this.list(qw);

        Map<String, List<ScheduleMemory>> memoryMap = list.stream().collect(Collectors.groupingBy(x -> x.getCategoryName()));
        List<MemoryDataVo> segmentVoList = new ArrayList<>();
        memoryMap.forEach((key, value) -> {
            MemoryDataVo memoryDataVo = new MemoryDataVo();
            memoryDataVo.setTitle(key);
            memoryDataVo.setSegments(value.size()>0
                    ?value.stream().map(x->{
                SegmentVo segmentVo = new SegmentVo();
                segmentVo.setId(x.getId());
                segmentVo.setTitle(x.getTitle());
                segmentVo.setReadNum(x.getReadNum());
                if(x.getReadNum()>10){
                    segmentVo.setIsShow(false);
                }
                return segmentVo;
            }).filter(x->x.getIsShow()).collect(Collectors.toList())
                    :new ArrayList<>());
            memoryDataVo.setSegmentCount(memoryDataVo.getSegments().size());
            if(memoryDataVo.getSegmentCount()==0){
                memoryDataVo.setType(2);
            }
            segmentVoList.add(memoryDataVo);
        });
        return segmentVoList;
    }

    @Override
    public void saveMemory(SegmentQuery query) {

        ScheduleMemory byId = this.getById(query.getId());
        if (Objects.nonNull(byId)) {
            byId.setContent(query.getContent());
            this.updateById(byId);
        }
    }


    @Override
    public ReadNumVo clock(Integer id) {

        ReadNumVo readNumVo = new ReadNumVo();
        ScheduleMemory article = this.getById(id);
        if (article == null) return null;

        article.setReadNum(article.getReadNum() + 1);
        this.updateById(article);
        readNumVo.setReadNum(Long.valueOf(article.getReadNum()));
        Integer reward = 0;
        try {
            reward = scheduleRewardService.saveHabitReward();
            String rewardStr;
            switch (reward){
                case 0:
                    rewardStr = "很遗憾没有获得积分";
                    break;
                case 1:
                    rewardStr = "恭喜你获得了"+reward+"积分";
                    break;
                case 2:
                    rewardStr = "恭喜你获得了"+reward+"积分";
                    break;
                case 7:
                    rewardStr = "恭喜你获得了游龙积分";
                    break;
                case 9:
                    rewardStr = "恭喜你获得了至尊积分";
                    break;
                case 10:
                    rewardStr = "恭喜你获得了球王积分";
                    break;
                default:
                    rewardStr = "很遗憾没有获得积分";
            }
            readNumVo.setReward(rewardStr);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return readNumVo;
    }

    @Override
    public void saveDocument(MemoryDataQuery query) {
        List<String> strings = TextSplitterUtil.splitText(query.getText());
        for (int i = 0; i < strings.size(); i++) {
            ScheduleMemory scheduleMemory = new ScheduleMemory();
            scheduleMemory.setCategoryName(query.getTitle());
            scheduleMemory.setContent(strings.get(i));
            scheduleMemory.setReadNum(1);
            scheduleMemory.setTitle(query.getTitle()+"-"+(i+1));
            this.save(scheduleMemory);
        }
    }

    @Override
    public void deleteDocument(Integer id) {

        this.removeById(id);
    }

    @Override
    public List<SegmentVo>  getDocumentSegments(String title) {

        LambdaQueryWrapper<ScheduleMemory> qw = new LambdaQueryWrapper<>();
        qw.eq(ScheduleMemory::getCategoryName,title);
        List<ScheduleMemory> list = this.list(qw);
        List<SegmentVo> res = list.stream().map(x -> {
            SegmentVo segmentVo = new SegmentVo();
            segmentVo.setId(x.getId());
            segmentVo.setOrder(Objects.isNull(x.getContent()) ? 0 : x.getContent().length());
            segmentVo.setTitle(x.getTitle());
            segmentVo.setContent(x.getContent());
            segmentVo.setReadNum(x.getReadNum());
            if (x.getReadNum() > 10) {
                segmentVo.setIsShow(false);
            }
            return segmentVo;
        }).filter(x->x.getIsShow()).collect(Collectors.toList());

        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void mergeMemory(MergeQuery query) {

        List<Integer> ids = new ArrayList<>();
        ids.add(query.getId());
        ids.addAll(query.getMergeIds());
        List<ScheduleMemory> scheduleMemories = this.listByIds(ids);
        StringBuilder stringBuilder = new StringBuilder();
        scheduleMemories.forEach(x->{
            stringBuilder.append(x.getContent());
        });
        LambdaUpdateWrapper<ScheduleMemory> qw = new LambdaUpdateWrapper<>();
        qw.eq(ScheduleMemory::getId,query.getId());
        qw.set(ScheduleMemory::getContent,stringBuilder.toString());
        this.update(qw);

        this.removeBatchByIds(query.getMergeIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMemories(String title) {

        LambdaQueryWrapper<ScheduleMemory> eq = new LambdaQueryWrapper<ScheduleMemory>().eq(ScheduleMemory::getCategoryName, title);
        this.remove(eq);
    }


}
